package com.skj.server ;

import java.io.IOException;
import java.io.*;

import javax.servlet.http.*;
import com.google.appengine.api.datastore.* ;

@SuppressWarnings("serial")
public class ResourceServlet extends HttpServlet
{
	private ResourceDatabase database ;
	
	private String 	resURI ;				// Resource URI
	private String 	resMIMEType ;			// Resource MIME Type
	private Blob	resContent ;			// Resource Content
	private int		resLength ;				// Resource Length in Bytes
	
	public ResourceServlet()
	{
		database = new ResourceDatabase() ;
	}
	
	// Creates a resource
	public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		resLength  	= req.getContentLength() ;
		resURI 		= req.getRequestURI() ;
		resMIMEType = req.getContentType() ;
		
		resContent = getContent(req.getInputStream()) ;
		
		database.createTextData(resURI, resMIMEType, resContent) ;
		
		resp.setContentType("text/plain");
		resp.getWriter().println(resLength + " BYTES DATA POSTED");
		resp.getWriter().println(req.getCharacterEncoding()) ;
	}
	
	// Retrieves a resource
	public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		Resource resource = database.retrieveTextData(req.getRequestURI()) ;
		
		if(resource != null)
		{
			resURI		= resource.getLocation() ;
			resMIMEType = resource.getMimeType() ;
			resContent	= resource.getContent() ;
			
			resp.setContentType(resMIMEType);
			resp.getOutputStream().write(resContent.getBytes()) ;
		}
		else
		{
			resp.setContentType("text/plain");
			resp.getWriter().println("No Such Resource Exists");
		}
	}
	
	// Updates a resource
	public void doPut(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		resp.setContentType("text/plain");
		
		Blob content  = getContent(req.getInputStream()) ;		
		database.updateTextData(req.getRequestURI(), content) ;
		
		resp.getWriter().println("DATA UPDATED");
	}
	
	// Deletes a resource
	public void doDelete(HttpServletRequest req, HttpServletResponse resp)throws IOException
	{
		database.deleteTextData(req.getRequestURI()) ;
		
		resp.setContentType("text/plain");
		resp.getWriter().println("DATA DELETED");
	}
	
	private Blob getContent(InputStream is)
	{	
		BufferedInputStream bis ;
		byte [] b ;
		
		try
		{
			bis = new BufferedInputStream(is) ;
			b = new byte[resLength] ;
			bis.read(b, 0, resLength) ;
			
			Blob blob = new Blob(b) ;
			
			return blob ;
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
		}
		
		return null ;
	}
}